//
//  OMOrderDetailTabsViewController.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/5/12.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMOrderDetailTabsViewController.h"

#import "OMOrderDetailViewController.h"
#import "FTSlideBar.h"

#import "OMOrderDetailResponse.h"
#import "OMOrderLogsDelegater.h"
#import "OMOrderDetailDelegater.h"

#import "OMOrderButtonAdapter.h"
#import "OMOrderButtonActionHelper.h"

#import "OMScrollView.h"

#define kButtonBaseTag 100
@interface OMOrderDetailTabsViewController () <FTSlideBarDelegate,FTSlideBarDataSource,UIScrollViewDelegate>
@property (nonatomic, strong) OMOrderDetailResponse *detailResponse;
@property (nonatomic, strong) UITableView *logsTableView;
@property (nonatomic, strong) OMOrderLogsDelegater *logsDelegater;
@property (nonatomic, strong) UITableView *detailTableView;
@property (nonatomic, strong) OMOrderDetailDelegater *detailDelegater;
@property (nonatomic, strong) OMScrollView *pagingView;

@property (nonatomic, strong) FTSlideBar *slideBar;
@property (nonatomic, strong) NSArray *titles;
@end

@implementation OMOrderDetailTabsViewController
- (NSString *)orderSn
{
    if (!_orderSn) {
        _orderSn = @"1111";
    }
    return _orderSn;
}


- (void)viewDidLoad {

    [super viewDidLoad];

    self.titles = @[@"订单状态",@"订单详情"];
    self.title = @"订单详情";

    self.slideBar = [[FTSlideBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, FT_SIZE(70))];
    self.slideBar.dataSource = self;
    self.slideBar.delegate = self;
    self.slideBar.backgroundColor = SM_whiteColor;
    [self.view addSubview:self.slideBar];

    self.pagingView = [OMScrollView new];
    self.pagingView.contentSize = CGSizeMake(SM_SCREEN_WIDTH*2, 0);
    self.pagingView.bounces = NO;
    self.pagingView.pagingEnabled = true;
    self.pagingView.delegate = self;
    self.pagingView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.pagingView];
    [self.pagingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom).offset(FT_SIZE(70));
        make.left.right.bottom.equalTo(@0);
    }];

    self.logsDelegater = [[OMOrderLogsDelegater alloc]initWithTableView:self.logsTableView];
    [self.pagingView addSubview:self.logsTableView];
    self.logsTableView.contentInset = UIEdgeInsetsMake(0, 0, SM_SIZE(120), 0);

    self.detailDelegater = [[OMOrderDetailDelegater alloc]initWithTableView:self.detailTableView];
    [self.pagingView addSubview:self.detailTableView];
    self.detailTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.detailTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, SM_SIZE(20))];
    self.detailTableView.contentInset = UIEdgeInsetsMake(0, 0, SM_SIZE(120), 0);

    [self getOrderDetail];
    self.slideBar.selectedIndex = MIN(1,self.selectedIndex);

    @weakify(self);
    [SMNotificationMonitorRACSignal(OMORDER_NEED_REFRESH_NOTIFICATION) subscribeNext:^(id x) {
        @strongify(self);
        [self getOrderDetail];
    }];
}

UIView *bar = nil;
- (void)removeButton
{
    [bar removeFromSuperview];
    bar = nil;
}

- (void)setupButton
{
    NSMutableArray <OMOrderButtonTitle*>*buttonTitles = [[OMOrderButtonAdapter buttonTitlesWithStatus:self.detailResponse.order.status showInList:NO] mutableCopy];

    CGFloat height = SM_SIZE(120);
    CGFloat detal = SM_SIZE(30);
    CGFloat width = (SM_SCREEN_WIDTH-detal*(buttonTitles.count+1))/buttonTitles.count;

    if (bar) {
        [self removeButton];
    }
    bar = [UIView new];
    bar.backgroundColor = SM_whiteColor;
    bar.hidden = !buttonTitles.count;
    [self.view addSubview:bar];
//    [self.logsTableView setContentInset:UIEdgeInsetsMake(0, 0, height, 0)];
    [bar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.height.equalTo(@(height));
    }];

    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [bar addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        make.height.equalTo(@.5f);
    }];


    for (NSUInteger i = 0; i < buttonTitles.count; i ++) {

        BOOL isFill = buttonTitles[i].isFullFill;
        UIButton *button = [UIButton new];

        button = [[UIButton alloc]initWithFrame:CGRectMake(SM_SCREEN_WIDTH-(i+1)*(width+detal), SM_SIZE(20), width, height-SM_SIZE(20)*2)];

        [button setTitle:buttonTitles[i].desc forState:UIControlStateNormal];
        if (self.detailResponse.order.paymentMethodType) {
            if ([buttonTitles[i].desc isEqualToString:@"申请退款"]) {
                [button setTitle:@"取消订单" forState:UIControlStateNormal];
            }
        }

        [button setTitleColor:SM_blackColor forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:isFill?SM_sangouColor:SM_whiteColor] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:RGBACOLOR(0, 0, 0, .26)] forState:UIControlStateDisabled];

        button.titleLabel.font = SM_CFont(33);
        [button addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];

        [button setTag:i + kButtonBaseTag];
        button.layer.cornerRadius = 4.f;
        button.clipsToBounds = true;
        if (!isFill) {
            button.layer.borderWidth = 1.f;
            button.layer.borderColor = SM_blackColor.CGColor;
        }

        [bar addSubview:button];
    }
}

- (void)submitAction:(UIButton *)sender
{
    [OMOrderButtonActionHelper actionWithButton:sender Order:self.detailResponse.order];
}

- (void)reloadDataFromNetWork
{
    [self getOrderDetail];
}

- (void)getOrderDetail
{
    [self.task cancel];
    [self startAnimating:YES];
    self.task =
    [KTHttpUtils GET_NOCACHE:@"member/order/view.jhtml"
                  parameters:@{@"sn":self.orderSn}
                    progress:nil
                  completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        if (isSuccess) {

            OMOrderDetailResponse *response = [OMOrderDetailResponse mj_objectWithKeyValues:responseObject[OMDatumKey]];
            NSString *imageUrl = [responseObject[OMImagePrefix]isKindOfClass:[NSString class]]?responseObject[OMImagePrefix]:@"";
            for (OMOrderItem *orderItem in response.order.orderItems) {
                orderItem.image = [imageUrl.length?imageUrl:@""stringByAppendingString:orderItem.image?:@""];
            }
            if (response.order.refunds.count) {
                response.order.refundsId = response.order.refunds[0].id;
            }
            self.detailResponse = response;
            [self startAnimating:NO];

        }else {

            [self showNetWorkError];
        }
        [self.pagingView setContentOffset:CGPointMake(SM_SCREEN_WIDTH*self.selectedIndex, 0) animated:NO];
    }];
}

#pragma mark - Setters
- (void)setDetailResponse:(OMOrderDetailResponse *)detailResponse
{
    _detailResponse = detailResponse;
    self.detailDelegater.response = detailResponse;
    self.logsDelegater.response = detailResponse;
    [self setupButton];
}


#pragma mark - Getters
- (UITableView *)logsTableView
{
    if (!_logsTableView) {
        _logsTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SM_SCREEN_WIDTH, SM_SCREEN_HEIGHT-64-FT_SIZE(70)) style:UITableViewStyleGrouped];
        _logsTableView.backgroundColor = SM_backGroundColor;
        _logsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _logsTableView.tableFooterView  = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.bounds.size.width, SM_SIZE(50))];
        _logsTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, DBL_EPSILON)];

    }
    return _logsTableView;
}

- (UITableView *)detailTableView
{
    if (!_detailTableView) {
        _detailTableView = [[UITableView alloc]initWithFrame:CGRectMake(SM_SCREEN_WIDTH, 0, SM_SCREEN_WIDTH, SM_SCREEN_HEIGHT-64-FT_SIZE(70)) style:UITableViewStyleGrouped];
        _detailTableView.backgroundColor = SM_backGroundColor;
        _detailTableView.separatorColor = SM_placeholdColor;
        _detailTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, DBL_EPSILON)];
        _detailTableView.tableFooterView  = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.bounds.size.width, SM_SIZE(50))];
    }
    return _detailTableView;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSUInteger index = round(scrollView.contentOffset.x/scrollView.frame.size.width);
    self.slideBar.selectedIndex = index;
}
#pragma mark - FTSlideBarDelegate
- (void)didSelectItemAtIndex:(NSUInteger)index
{
    [self.pagingView setContentOffset:CGPointMake(SM_SCREEN_WIDTH*index, 0) animated:true];
}

#pragma mark - FTSlideBarDataSource

- (NSUInteger)numOfItem
{
    return self.titles.count;
}

- (NSString *)itemTitleAtIndex:(NSUInteger)index
{
    return self.titles[index];
}

- (UIColor *)activeColor
{
    return SM_thumeColor;
}

- (UIColor *)normalColor
{
    return SM_blackColor;
}

- (UIFont *)itemFont
{
    return SM_CFont(29);
}
@end
